package com.example.vpnservicedemo.utils;

import android.net.VpnService;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.LinkedBlockingQueue;

public class PushPc {

    private LinkedBlockingQueue<byte[]> queue = new LinkedBlockingQueue<>();

    private VpnService vpnService;

    public PushPc(VpnService vpnService) {
        this.vpnService = vpnService;

        //开启读取队列线程
        ReadQueue readQueue = new ReadQueue();
        Thread thread = new Thread(readQueue);
        thread.setName("readQueueThread");
        thread.start();
    }

    class ReadQueue implements Runnable {

        private static final String host = "192.168.1.10";

        private static final int port = 18088;

        public ReadQueue() {

        }

        @Override
        public void run() {
            try (SocketChannel socketChannel = SocketChannel.open()) {

                vpnService.protect(socketChannel.socket());
                socketChannel.connect(new InetSocketAddress(host, port));


                while (!Thread.interrupted()) {
                    try {

                        byte[] take = queue.take();

                        socketChannel.write(ByteBuffer.wrap(take));



                    } catch (InterruptedException e) {
                        e.printStackTrace();

                        queue.clear();
                        queue = null;
                    }

                }

            } catch (Exception e) {
                System.out.println("连接异常:" + e.getMessage());
                e.printStackTrace();
            }

        }
    }

    public void pushData(byte[] data) {
        if(queue!=null){
            //添加时间戳合并数据
            long l = System.currentTimeMillis();
            ByteBuffer allocate = ByteBuffer.allocate(data.length + 8 + 4);
            allocate.putInt(data.length + 8);
            allocate.putLong(l);
            allocate.put(data);
            queue.offer(allocate.array());
        }


    }


}

